package com.itboye.ihomebank;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.util.MalformedJsonException;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.itboye.ihomebank.activity.key.ActivityAddICCard;
import com.itboye.ihomebank.activity.key.ActivityGuanLiKey;
import com.itboye.ihomebank.activity.key.ActivityICCardList;
import com.itboye.ihomebank.activity.key.ActivityKeyYuYue;
import com.itboye.ihomebank.activity.key.ActivityPuTongKey;
import com.itboye.ihomebank.activity.key.ActivitySendKey;
import com.itboye.ihomebank.activity.key.ActivitySheBei;
import com.itboye.ihomebank.activity.key.ActivityYongHu;
import com.itboye.ihomebank.activity.key.TTLockTimeTest;
import com.itboye.ihomebank.activity.key.UpdateKeyActivity;
import com.itboye.ihomebank.activity.keytwo.KeyGuanLiActivity;
import com.itboye.ihomebank.activity.keytwo.SheBeiTwoActivity;
import com.itboye.ihomebank.activity.keytwo.KeyZuHuActivity;
import com.itboye.ihomebank.activity.keytwo.TostKey;
import com.itboye.ihomebank.activity.login.AddDeviceActivity;
import com.itboye.ihomebank.adapter.KeyAdapter;
import com.itboye.ihomebank.adapter.key.KeyTwoAdapter;
import com.itboye.ihomebank.base.BaseFragment;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.base.MyApplcation;
import com.itboye.ihomebank.base.ptr.BasePtr;
import com.itboye.ihomebank.bean.BangDingBean;
import com.itboye.ihomebank.bean.DownBeifenBean;
import com.itboye.ihomebank.bean.KeyBean;
import com.itboye.ihomebank.bean.KeysBean;
import com.itboye.ihomebank.bean.OpenIdBean;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.bean.SIDBean;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.db.MyKeyService;
import com.itboye.ihomebank.interfaces.IRefreshAfterAlert;
import com.itboye.ihomebank.presenter.KeyPresenter;
import com.itboye.ihomebank.presenter.KeyTwoPresenter;
import com.itboye.ihomebank.presenter.UserPresenter;
import com.itboye.ihomebank.ttKey.BleConstant;
import com.itboye.ihomebank.ttKey.BleSession;
import com.itboye.ihomebank.ttKey.DaoMaster;
import com.itboye.ihomebank.ttKey.DaoSession;
import com.itboye.ihomebank.ttKey.DbService;
import com.itboye.ihomebank.ttKey.Key;
import com.itboye.ihomebank.ttKey.KeyDao;
import com.itboye.ihomebank.ttKey.MyPreference;
import com.itboye.ihomebank.ttKey.Operation;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.SPUtils;
import com.itboye.ihomebank.util.SaveKeyBean;
import com.itboye.ihomebank.util.UIAlertView;
import com.itboye.ihomebank.util.dialog.RxDialog;
import com.itboye.ihomebank.widget.VerificationCodeView;
import com.sitri.sdk.SLock;
import com.sitri.sdk.callback.visible.CommonCallback;
import com.sitri.sdk.model.ID;
import com.sitri.sdk.model.ResultData;
import com.sitri.sdk.model.ResultError;
import com.ttlock.bl.sdk.api.TTLockAPI;
import com.ttlock.bl.sdk.callback.TTLockCallback;
import com.ttlock.bl.sdk.entity.Error;
import com.ttlock.bl.sdk.scanner.ExtendedBluetoothDevice;
import com.ttlock.bl.sdk.util.LogUtil;

import org.greenrobot.greendao.database.Database;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import java.util.TimeZone;

import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrDefaultHandler2;
import in.srain.cube.views.ptr.PtrFrameLayout;

import static com.alibaba.mobileim.channel.constant.WXType.WXPwdType.openid;
import static com.itboye.ihomebank.activity.key.ActivitySheBei.adminKeyboardPwd;
import static com.itboye.ihomebank.activity.key.ActivitySheBei.adminPs;
import static com.itboye.ihomebank.activity.key.ActivitySheBei.unlockKey;
import static com.itboye.ihomebank.base.MyApplcation.curActivity;
import static com.itboye.ihomebank.ttKey.Operation.UNLOCK;
import static com.itboye.ihomebank.util.SPUtils.get;
import static com.ttlock.bl.sdk.util.GsonUtil.gson;
import static java.lang.Long.parseLong;
import static java.lang.System.currentTimeMillis;

/**
 * 钥匙
 */
public class KeyFragment extends BaseFragment implements OnClickListener, Observer, CommonCallback{
    View v_statusbar;
    TextView save;//最右边的
    ImageView close_icon;
    TextView add_shap_title_tv;
    ListView xlistview;
    PtrFrameLayout commend_anchor_ptr_baima;
    LinearLayout liner_nokey;//没有钥匙的时候
    LinearLayout li_search;//搜索

    TextView mykey_add, mykey_yuyue;
    public static Context mContext;
    EditText mykey_sousuo;
    public static DaoSession daoSession;


    /**
     * 通通锁
     */
    public static TTLockAPI mTTLockAPI;
    /**
     * 蓝牙操作
     */
    public static BleSession bleSession = BleSession.getInstance(UNLOCK, null);
    private static boolean DBG = true;
    public static KeyDao keyDao;
    /**
     * 当前操作的key
     */
    private Key curKey;

    private Handler handler = new Handler();

    KeyPresenter keyPresenter;
    KeyTwoPresenter keyTwoPresenter;
    private String uid, mac;

    UserPresenter userPresenter;
    BangDingBean bean;
    private KeyTwoAdapter adapter;// 钥匙适配器
    private List<KeysBean> kensBean_baima;//钥匙列表数据
    private List<Key> keys;//本地缓存的钥匙

    public static String deKeyId;// 长按删除的是哪一个钥匙
    public static String lockKeyId;// 长按删除keyid
    public static String lockKeyType = "";// 长按删除的是白马锁（6587）还是  科技侠（6323）
    public static String lockKeyMac = "";//长按的mac
    public String jiebangKey;//长按解绑的是哪个钥匙

    MyKeyService myKeyService;//我的钥匙列表数据库
    private boolean operateSuccess = true;

    private UIAlertView uiAlertView;//删除钥匙
    private UIAlertView uiAlertView01;//选择
    /**
     * 记录当前点击的key
     */
    public static Key curKeys;
    /**
     * 记录当前长按点击的key
     */
    public static Key keysChangAn;

    private String lockid;
    private String locMac;

    public static KeyFragment context;

    DownBeifenBean beifenBean;//下载的备份钥匙（为了解决v2升级成v3的时候  导致v3数据列表没有解绑的数据）

    public static int clockProduct=1;
    public  int diconectNum=0;

    //科技侠
    PtrFrameLayout commend_anchor_ptr_kejixia;
    ListView xlistview_kejixia;
    LinearLayout liner_nokey_kejixia;
    TextView mykey_add_kejixia,mykey_yuyue_kejixia;

    private KeyTwoAdapter kejiAdapter;// 钥匙适配器
    private List<KeysBean> kensBean_kejixia;//钥匙列表数据
    private List<Key> keys_kejixia;//本地缓存的钥匙

    private int icardNum;
    private  InputMethodManager imm;

    private String alisa;

    private boolean isLock;

    private String sid="";

    private int cz;
    public static KeyFragment getInstance() {
        return context;
    }

    @Override
    public int initView() {
        return R.layout.activity_my_key;
    }

    @Override
    public void onMyActivityCreated() {
        init();
    }

    private void init() {
        SLock.getServices().setIsDebug(true);
        SLock.getServices().setCommonCallback(this);

        imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);

        setStatusBarHeight(v_statusbar);
        setStatusBarColor(v_statusbar,getActivity().getResources().getColor(R.color.title_blue));
        close_icon.setImageResource(R.drawable.keysearch);
        save.setVisibility(View.VISIBLE);
        save.setText("切换锁");

        context = this;
        mContext = getActivity();
        keyPresenter = new KeyPresenter(this);
        keyTwoPresenter= new KeyTwoPresenter(this);
        userPresenter = new UserPresenter(this);
        uid = get(getActivity(), null, SPContants.USER_ID, "") + "";
        initTTLock();
        initGreenDao();


       //请求打开蓝牙
        mTTLockAPI.requestBleEnable(getActivity());
        LogUtil.d("启动蓝牙服务", DBG);
        mTTLockAPI.startBleService(getActivity());
        LogUtil.d("请求位置权限", DBG);
        //请求位置权限成功打开蓝牙
//        if (requestPermission(Manifest.permission.ACCESS_COARSE_LOCATION)) {
//            mTTLockAPI.startBTDeviceScan();
//        }
        //初始化显示 白马或者科技侠锁界面

        //加载切换服务器弹框
//        showAlert();

        initClock();
        initKejixiaSlock();
        initBaimaSlock();
        //登录的广播
        IntentFilter filter = new IntentFilter();
        filter.addAction("changeavart");
        filter.addAction(BleConstant.ADD_ALISA);
        getActivity().registerReceiver(loginReceiver, filter);
        //上传开锁记录，如果在没网的情况的开锁记录，和锁ID存在本地，在有网的时候再上传，上传之后清空掉数据
        try {
            String records = get(getActivity(), null, SPContants.RECORDS, "") + "";
            String records_lockid = get(getActivity(), null, SPContants.RECORDS_LOCKID, "") + "";
            int power= (int) SPUtils.get(getActivity(),null,SPContants.BATTERY,0);
            sid=SPUtils.get(MyApplcation.ctx,null,SPContants.LOCK_SESSION,"")+"";

            if (!records.equals("") || !records_lockid.equals("")) {
                if ("".equals(sid)){
                    userPresenter.uploadHistoryOfUnlock(get(getActivity(), null, SPContants.USER_ID, "") + "", records_lockid, records, "1",System.currentTimeMillis()/1000,power);//上传开锁记录

                }else {
                    userPresenter.uploadHistoryOfUnlock(sid, records_lockid, records, "1",System.currentTimeMillis()/1000,power);//上传开锁记录

                }
            }
        } catch (Exception e) {
        }

        mykey_sousuo.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                //当actionId == XX_SEND 或者 XX_DONE时都触发
                //或者event.getKeyCode == ENTER 且 event.getAction == ACTION_DOWN时也触发
                //注意，这是一定要判断event != null。因为在某些输入法上会返回null。
                if (actionId == EditorInfo.IME_ACTION_SEND
                        || actionId == EditorInfo.IME_ACTION_DONE
                        || (event != null && KeyEvent.KEYCODE_ENTER == event.getKeyCode() && KeyEvent.ACTION_DOWN == event.getAction())) {
                    //处理事件
                    if (!mykey_sousuo.getText().toString().equals("")){
                        if (clockProduct%2==1) {//科技侠
                            cz=2;
                            sid=SPUtils.get(MyApplcation.ctx,null,SPContants.LOCK_SESSION,"")+"";
                            isLock= (boolean) SPUtils.get(MyApplcation.ctx,null,SPContants.ISLOCK,false);
                            if ("".equals(sid)){
                                keyPresenter.myKey(uid, mykey_sousuo.getText().toString().trim(),isLock);
                            }else {
                                keyPresenter.myKey(sid, mykey_sousuo.getText().toString().trim(),isLock);
                            }


                            userPresenter.getOpenId(uid);//获取科技侠openid
                        }else { //白马锁
                            keyTwoPresenter.onMyKey(uid,  mykey_sousuo.getText().toString().trim());
                        }
                    }else {
                        if (clockProduct%2==1) {//科技侠
                            cz=2;
                            sid=SPUtils.get(MyApplcation.ctx,null,SPContants.LOCK_SESSION,"")+"";
                            isLock= (boolean) SPUtils.get(MyApplcation.ctx,null,SPContants.ISLOCK,false);

                            if ("".equals(sid)){
                                keyPresenter.myKey(uid, "",isLock);
                            }else {
                                keyPresenter.myKey(sid, "",isLock);
                            }

                            userPresenter.getOpenId(uid);//获取科技侠openid
                        }else { //白马锁
                            keyTwoPresenter.onMyKey(uid, "");
                        }
                    }
                }
                return false;
            }
        });

    }

    //初始化显示白马锁或者科技侠锁
    private void initClock() {
        if (clockProduct%2==1){//科技侠
            add_shap_title_tv.setText("住家锁(面板锁)");
            commend_anchor_ptr_kejixia.setVisibility(View.VISIBLE);
            commend_anchor_ptr_baima.setVisibility(View.GONE);
//            initKejixiaSlock();
        }else {
            add_shap_title_tv.setText("住家锁(锁芯锁)");
            commend_anchor_ptr_kejixia.setVisibility(View.GONE);
            commend_anchor_ptr_baima.setVisibility(View.VISIBLE);
//            initBaimaSlock();
        }

    }


    private void initKejixiaSlock() {

        BasePtr.setRefreshOnlyStyle(commend_anchor_ptr_kejixia);//设置上拉下拉刷新
        uid = get(getActivity(), null, SPContants.USER_ID, "") + "";
        keys_kejixia = new ArrayList();
        beifenBean = new DownBeifenBean();


        kensBean_kejixia = new ArrayList<>();


        //  keys = DbService.getKeysByLockAlias("");

        kejiAdapter = new KeyTwoAdapter(getActivity(),keys_kejixia);
        xlistview_kejixia.setAdapter(kejiAdapter);
        commend_anchor_ptr_kejixia.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                sid=SPUtils.get(MyApplcation.ctx,null,SPContants.LOCK_SESSION,"")+"";
                isLock= (boolean) SPUtils.get(MyApplcation.ctx,null,SPContants.ISLOCK,false);
                cz=2;
                if (!mykey_sousuo.getText().toString().equals("")){
                    if ("".equals(sid)){
                        keyPresenter.myKey(uid, mykey_sousuo.getText().toString().trim(),isLock);
                    }else {
                        keyPresenter.myKey(sid, mykey_sousuo.getText().toString().trim(),isLock);
                    }
                    userPresenter.getOpenId(uid);//获取科技侠openid
                }else {
                    if ("".equals(sid)){
                        keyPresenter.myKey(uid, mykey_sousuo.getText().toString().trim(),isLock);
                    }else {
                        keyPresenter.myKey(sid, mykey_sousuo.getText().toString().trim(),isLock);
                    }
                    userPresenter.getOpenId(uid);//获取科技侠openid
                }

            }
        });
        commend_anchor_ptr_kejixia.autoRefresh();
        initsKejixiaList();
    }

    private void initsKejixiaList() {
        xlistview_kejixia.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                keysChangAn = keys_kejixia.get(position);
                deKeyId = keys_kejixia.get(position).getKeyId();
                lockKeyId = keys_kejixia.get(position).getLockId();
                lockKeyType = keys_kejixia.get(position).getLock_type();
                lockKeyMac = keys_kejixia.get(position).getLockMac();
                jiebangKey = keys_kejixia.get(position).getLockMac();
                final String types = keys_kejixia.get(position).getTypes();

                uiAlertView = new UIAlertView(getActivity(), types.equals("0") ? "解绑管理员?" : "删除钥匙",
                        types.equals("0") ? "是否解绑管理员?" : "是否删除钥匙", "是", "取消");
                uiAlertView.show();
                uiAlertView.setClicklistener(new UIAlertView.ClickListenerInterface() {
                    @Override
                    public void doLeft() {
                        if (types.equals("0")) {//是否是管理员
                            showProgressDialog("正在删除，请保持蓝牙和锁链接...", true);
//                            if (lockKeyType.equals("6323")) {//科技侠
//                                if (keysChangAn.getAdminPs() == null || keysChangAn.getAdminPs().equals("") || keysChangAn.getUnlockKey() == null || keysChangAn.getUnlockKey().equals("")) {
//                                    keyPresenter.getDownKeyBeiFen(uid, lockKeyId, deKeyId);
//                                } else {
//                                    KeyFragment.bleSession.setOperation(Operation.RESET_LOCK);
//                                    KeyFragment.mTTLockAPI.connect(keys_kejixia.get(position).getLockMac());
////                                    userPresenter.unbindLock(uid, lockKeyId, deKeyId, "");
//                                }
//                            }
                            KeyFragment.bleSession.setOperation(Operation.RESET_LOCK);
                            KeyFragment.mTTLockAPI.connect(keys_kejixia.get(position).getLockMac());
                        }
                        else {
                            ByAlert.alert("非管理员不能删除钥匙");
//                            KeyFragment.bleSession.setOperation(Operation.RESET_LOCK);
//                            KeyFragment.mTTLockAPI.connect(keys_kejixia.get(position).getLockMac());
//                            KeyFragment.bleSession.setLockmac(keys_kejixia.get(position).getLockMac());
//                            userPresenter.unbindLock(uid, keys_kejixia.get(position).getLockId(), keys_kejixia.get(position).getKeyId(), "");
                        }
                        uiAlertView.dismiss();
                    }

                    @Override
                    public void doRight() {
                        uiAlertView.dismiss();
                    }
                });
                return true;
            }
        });
        xlistview_kejixia.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                curKeys = keys_kejixia.get(position);
                Log.d("=====keji==",curKeys.toString());
                lockid = keys_kejixia.get(position).getLockId();
                locMac = keys_kejixia.get(position).getLockMac();
                String type = keys_kejixia.get(position).getTypes();
                String status = keys_kejixia.get(position).getStatus();
                String lock_type = keys_kejixia.get(position).getLock_type();
                if (status.equals("110402")) {
                    ByAlert.alert("该钥匙待接受");
                    return;
                }
                if (status.equals("110405")) {
                    ByAlert.alert("该钥匙已冻结");
                    return;
                }
                if (status.equals("110408")) {
                    ByAlert.alert("该钥匙已删除");
                    return;
                }
                if (status.equals("110410")) {
                    ByAlert.alert("该钥匙已重置");
                    return;
                }


                if (keys_kejixia.get(position).getEndDate()!=0){
                    Long dq_time = System.currentTimeMillis()/1000;//当前时间
                    Long sx_time = keys_kejixia.get(position).getEndDate();//锁的实效时间
                    if(dq_time>=sx_time){
                        ByAlert.alert("该钥匙已失效");
                        return;
                    }
                }
                if (lock_type.equals("6587")){//白马锁
                    Intent intent = new Intent(getActivity(), KeyGuanLiActivity.class);
                    intent.putExtra("activity","one");
                    intent.putExtra("leixing",type);
                    startActivityForResult(intent, 110);
                }else{//科技侠
//                    if (type.equals("0")){
//                        Intent intent = new Intent(getActivity(),
//                                ActivityGuanLiKey.class);
//                        startActivity(intent);
//                    }else{
//                        Intent intent = new Intent(getActivity(),
//                                ActivityPuTongKey.class);
//                        startActivity(intent);
//                    }

                    Intent intent = new Intent(getActivity(),
                            ActivityGuanLiKey.class);
                    intent.putExtra("activity","one");
                    intent.putExtra("leixing",type);
                    intent.putExtra("position",position);
                    startActivity(intent);
                }

            }
        });
//        //模糊搜索
//        mykey_sousuo.addTextChangedListener(new TextWatcher() {
//            @Override
//            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//            }
//
//            @Override
//            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                String kword = mykey_sousuo.getText().toString();
//                List<Key> localKey = new ArrayList<Key>();
//                localKey = DbService.getKeysByLockAlias(kword);
//                kejiAdapter = new KeyTwoAdapter(getActivity(), localKey);
//                xlistview_kejixia.setAdapter(kejiAdapter);
//            }
//
//            @Override
//            public void afterTextChanged(Editable s) {
//            }
//        });
    }


    private void initBaimaSlock() {

//        commend_anchor_ptr_baima.(this);
        BasePtr.setRefreshOnlyStyle(commend_anchor_ptr_baima);//设置上拉下拉刷新


        keys = new ArrayList<Key>();
        beifenBean = new DownBeifenBean();
        uid = get(getActivity(), null, SPContants.USER_ID, "") + "";
        sid=SPUtils.get(MyApplcation.ctx,null,SPContants.LOCK_SESSION,"")+"";

        kensBean_baima = new ArrayList<>();
        inits();
        initGreenDao();


        //  keys = DbService.getKeysByLockAlias("");

        adapter = new KeyTwoAdapter(getActivity(), keys);
        xlistview.setAdapter(adapter);


        commend_anchor_ptr_baima.setPtrHandler(new PtrDefaultHandler() {

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                cz=4;
                sid=SPUtils.get(MyApplcation.ctx,null,SPContants.LOCK_SESSION,"")+"";
                if ("".equals(sid)){
                    if (!mykey_sousuo.getText().toString().equals("")){
                        keyTwoPresenter.onMyKey(uid, mykey_sousuo.getText().toString().trim());
                    }else {
                        keyTwoPresenter.onMyKey(uid, "");
                    }
                }else {
                    if (!mykey_sousuo.getText().toString().equals("")){
                        keyTwoPresenter.onMyKey(sid, mykey_sousuo.getText().toString().trim());
                    }else {
                        keyTwoPresenter.onMyKey(sid, "");
                    }
                }

                         }
        });
        commend_anchor_ptr_baima.autoRefresh();
    }


    BroadcastReceiver loginReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {

            sid=SPUtils.get(MyApplcation.ctx,null,SPContants.LOCK_SESSION,"")+"";
            isLock= (boolean) SPUtils.get(MyApplcation.ctx,null,SPContants.ISLOCK,false);

            if (intent.getAction().equals(BleConstant.ADD_ALISA)){
                cz=1;
                uploadData();
            }else {
                cz=2;
                uid = SPUtils.get(getActivity(), null, SPContants.USER_ID, "") + "";
                if ("".equals(sid)){
                    keyPresenter.myKey(uid, mykey_sousuo.getText().toString().trim(),isLock);
                }else {
                    keyPresenter.myKey(sid, mykey_sousuo.getText().toString().trim(),isLock);
                }
                if ("".equals(sid)){
                    keyTwoPresenter.onMyKey(uid,"");
                }else {
                    keyTwoPresenter.onMyKey(sid,"");
                }
                userPresenter.getOpenId(uid);//获取科技侠openid
                if (adapter != null) {
                    adapter.notifyDataSetChanged();
                }
            }
        }
    };

    @Override
    public void onResume() {
        super.onResume();
        SLock.getServices().setIsDebug(true);
        SLock.getServices().setCommonCallback(this);


    }
    //onrestart 中刷新列表
    public void refreshList(){
            if (clockProduct%2==1) {//科技侠
                initKejixiaSlock();
            }else { //白马
                initBaimaSlock();
            }

    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(loginReceiver);
        mTTLockAPI.stopBleService(getActivity());
        SLock.getServices().disconnectBle();
    }

    /**
     * listview操作
     */
    private void inits() {
        xlistview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                keysChangAn = keys.get(position);
                deKeyId = keys.get(position).getKeyId();
                lockKeyId = keys.get(position).getLockId();
                lockKeyType = keys.get(position).getLock_type();
                lockKeyMac = keys.get(position).getLockMac();
                jiebangKey = keys.get(position).getLockMac();
                final String types = keys.get(position).getTypes();

                uiAlertView = new UIAlertView(getActivity(), types.equals("0") ? "解绑管理员?" : "删除钥匙",
                        types.equals("0") ? "是否解绑管理员?" : "是否删除钥匙", "是", "取消");
                uiAlertView.show();
                uiAlertView.setClicklistener(new UIAlertView.ClickListenerInterface() {
                    @Override
                    public void doLeft() {
                        cz=5;//解绑
                        sid=SPUtils.get(MyApplcation.ctx,null,SPContants.LOCK_SESSION,"")+"";
                        if (types.equals("0")) {//是否是管理员
                           if (lockKeyType.equals("6587")) {//白马云锁
                                showProgressDialog("正在解绑,请稍后......", false);
                                // SLock.getServices().unBindLock(lockKeyMac);//现在是交给后台进行删除操作了
                               if ("".equals(sid)){
                                   keyTwoPresenter.onUnbindLock(uid, lockKeyId, deKeyId, "");
                               }else {
                                   keyTwoPresenter.onUnbindLock(sid, lockKeyId, deKeyId, "");
                               }

                            }
                        } else {
                            if ("".equals(sid)){
                                keyTwoPresenter.onUnbindLock(uid, lockKeyId, deKeyId, "");
                            }else {
                                keyTwoPresenter.onUnbindLock(sid, lockKeyId, deKeyId, "");
                            }
                        }
                        uiAlertView.dismiss();
                    }

                    @Override
                    public void doRight() {
                        uiAlertView.dismiss();
                    }
                });
                return true;
            }
        });
        xlistview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                curKeys = keys.get(position);
                lockid = keys.get(position).getLockId();
                locMac = keys.get(position).getLockMac();
                String type = keys.get(position).getTypes();
                String status = keys.get(position).getStatus();
                String lock_type = keys.get(position).getLock_type();
                if (status.equals("110402")) {
                    ByAlert.alert("该钥匙待接受");
                    return;
                }
                if (status.equals("110405")) {
                    ByAlert.alert("该钥匙已冻结");
                    return;
                }
                if (status.equals("110408")) {
                    ByAlert.alert("该钥匙已删除");
                    return;
                }
                if (status.equals("110410")) {
                    ByAlert.alert("该钥匙已重置");
                    return;
                }
                if (keys.get(position).getEndDate()!=0){
                    Long dq_time = System.currentTimeMillis()/1000;//当前时间
                    Long sx_time = keys.get(position).getEndDate();//锁的实效时间
                    if(dq_time>=sx_time){
                        ByAlert.alert("该钥匙已失效");
                        return;
                    }
                }
                if (lock_type.equals("6587")){//白马锁
                    Intent intent = new Intent(getActivity(), KeyGuanLiActivity.class);
                    intent.putExtra("activity","one");
                    intent.putExtra("leixing",type);
                    startActivityForResult(intent, 110);
                }
//                else{//科技侠
//                    if (type.equals("0")){
//                        Intent intent = new Intent(getActivity(),
//                                ActivityGuanLiKey.class);
//                        startActivity(intent);
//                    }else{
//                        Intent intent = new Intent(getActivity(),
//                                ActivityPuTongKey.class);
//                        startActivity(intent);
//                    }
//                }

            }
        });
        //模糊搜索
//        mykey_sousuo.addTextChangedListener(new TextWatcher() {
//            @Override
//            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//            }
//
//            @Override
//            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                String kword = mykey_sousuo.getText().toString();
//                List<Key> localKey = new ArrayList<Key>();
//                localKey = DbService.getKeysByLockAlias(kword);
//                kejiAdapter = new KeyTwoAdapter(getActivity(), localKey);
//                xlistview_kejixia.setAdapter(kejiAdapter);
//            }
//
//            @Override
//            public void afterTextChanged(Editable s) {
//            }
//        });
    }

    /**
     * 通通锁初始化操作
     */
    public void initTTLock() {
        LogUtil.d("create TTLockAPI", DBG);
        mTTLockAPI = new TTLockAPI(mContext, mTTLockCallback);
    }

    /**
     * 数据库初始化
     */
    private void initGreenDao() {
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(getActivity(), "zhujias.db", null);
        Database db = helper.getWritableDb();
        daoSession = new DaoMaster(db).newSession();
        keyDao = daoSession.getKeyDao();
    }

    public static DaoSession getDaoSession() {
        return daoSession;
    }

    public void panduan(String uid) {

    }

    /**
     * 刷新
     */
    public void refresh() {
    }

    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.close_icon:// 搜索
                sid=SPUtils.get(MyApplcation.ctx,null,SPContants.LOCK_SESSION,"")+"";
                isLock= (boolean) SPUtils.get(MyApplcation.ctx,null,SPContants.ISLOCK,false);
                if (li_search.getVisibility()==View.GONE||li_search.getVisibility()==View.INVISIBLE){
                    li_search.setVisibility(View.VISIBLE);
                }else {
                    if (!mykey_sousuo.getText().toString().equals("")){
                        if (clockProduct%2==1) {//科技侠
                            cz=2;
                            if ("".equals(sid)){
                                keyPresenter.myKey(uid, mykey_sousuo.getText().toString().trim(),isLock);
                            }else {
                                keyPresenter.myKey(sid, mykey_sousuo.getText().toString().trim(),isLock);
                            }
                            userPresenter.getOpenId(uid);//获取科技侠openid
                        }else { //白马锁
                            cz=4;
                            if ("".equals(sid)){
                                keyTwoPresenter.onMyKey(uid,  mykey_sousuo.getText().toString().trim());
                            }else {
                                keyTwoPresenter.onMyKey(sid,  mykey_sousuo.getText().toString().trim());
                            }
                        }
                    }else { //未输入时
                        if (clockProduct%2==1) {//科技侠
                            cz=2;
                            if ("".equals(sid)){
                                keyPresenter.myKey(uid, "",isLock);
                            }else {
                                keyPresenter.myKey(sid, "",isLock);
                            }
                            userPresenter.getOpenId(uid);//获取科技侠openid
                        }else { //白马锁
                            cz=4;
                            if ("".equals(sid)){
                                keyTwoPresenter.onMyKey(uid, "");
                            }else {
                                keyTwoPresenter.onMyKey(sid, "");
                            }

                        }
                    }
                }
             break;
            case R.id.save://切换锁
                clockProduct++;
                if (clockProduct%2==1){//科技侠
                    add_shap_title_tv.setText("住家锁(面板锁)");
                    commend_anchor_ptr_kejixia.setVisibility(View.VISIBLE);
                    commend_anchor_ptr_baima.setVisibility(View.GONE);
                    initKejixiaSlock();
                }else {//白马锁
                    add_shap_title_tv.setText("住家锁(锁芯锁)");
                    commend_anchor_ptr_kejixia.setVisibility(View.GONE);
                    commend_anchor_ptr_baima.setVisibility(View.VISIBLE);
                    initBaimaSlock();
                }
                break;
            case R.id.mykey_add:// 添加钥匙
                    intent = new Intent(getActivity(), SheBeiTwoActivity.class);
                    startActivity(intent);
                break;
            case R.id.mykey_yuyue:// 预约安装
                intent = new Intent(getActivity(), ActivityKeyYuYue.class);
                startActivity(intent);
                break;

            case R.id.mykey_add_kejixia:// 添加科技侠钥匙
                    intent = new Intent(getActivity(), ActivitySheBei.class);
                    startActivity(intent);
                break;
            case R.id.mykey_yuyue_kejixia:// 预约科技侠安装
                intent = new Intent(getActivity(), ActivityKeyYuYue.class);
                startActivity(intent);
                break;
            default:

                break;
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == TTLockAPI.REQUEST_ENABLE_BT) {
                //打开蓝牙之后启动扫描
                mTTLockAPI.startBTDeviceScan();
            }
        }
        if (requestCode == 110 && resultCode == 110) {
            MainActivity.onSetFragment().setTabSelection(1);
        }
    }

    @Override
    public void update(Observable observable, Object data) {
        try {
            closeProgressDialog();
            // 隐藏软键盘
            imm.hideSoftInputFromWindow(mykey_sousuo.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            imm.hideSoftInputFromWindow(getActivity().getWindow().getDecorView().getWindowToken(), 0); //强制隐藏键盘

        } catch (Exception e) {
        }
        ResultEntity entity = handlerError(data);
        commend_anchor_ptr_baima.refreshComplete();//设置白马刷新完成
        commend_anchor_ptr_kejixia.refreshComplete();//设置 科技侠刷新完成
        if (entity != null) {
            if (entity.getEventType() == KeyPresenter.addMain_success) {
                ByAlert.alert("添加管理员成功");
                cz=2;
                SaveKeyBean.saveData("2", null);
                bean = (BangDingBean) entity.getData();
                sid=SPUtils.get(MyApplcation.ctx,null,SPContants.LOCK_SESSION,"")+"";
                isLock= (boolean) SPUtils.get(MyApplcation.ctx,null,SPContants.ISLOCK,false);
                if ("".equals(sid)){
                    keyPresenter.myKey(uid, "",isLock);
                }else {
                    keyPresenter.myKey(sid, "",isLock);
                }

                if (adapter != null) {
                    adapter.notifyDataSetChanged();
                }

            } else if (entity.getEventType() == KeyPresenter.addMain_fail) {

                if (entity.getData() instanceof ServerError||entity.getData() instanceof TimeoutError){//服务器失败
                    //切换 锁备用服务器
                    showAlert();
                }else {
                    ByAlert.alert("添加管理员失败");
                    Intent intent = new Intent(getActivity(), UpdateKeyActivity.class);
                    startActivity(intent);
                }

            } else if (entity.getEventType() == KeyPresenter.mykeys_success) {//我的钥匙 科技侠列表
                li_search.setVisibility(View.GONE);
                kensBean_kejixia = (List<KeysBean>) entity.getData();
                if (kensBean_kejixia.size()>0){
                    clockProduct=1;
                    initClock();
                }
                Log.d("=====keji==",kensBean_kejixia.toString());
                if (kensBean_kejixia != null) {
                    if (kensBean_kejixia.size() > 0) {
                        keys_kejixia.clear();
                        //清空本地并重新保存数据
                        DbService.deleteAllKey();
                        for (int i = 0; i < kensBean_kejixia.size(); i++) {
                            xlistview_kejixia.setVisibility(View.VISIBLE);
                            liner_nokey_kejixia.setVisibility(View.GONE);
                            //110401 正常使用  110402 待接受  110405 	已冻结  110408 已删除  110410 已重置
                            if (kensBean_kejixia.get(i).getStatus().equals("110408")||kensBean_kejixia.get(i).getStatus().equals("110410")){
                                //锁钥匙已被重置或删除
                            }else {
                                Key key = new Key();
                                key.setAccessToken(MyPreference.getStr(mContext,
                                        MyPreference.ACCESS_TOKEN));
                                if (kensBean_kejixia.get(i).getType().equals("0")) {
                                    key.setAdmin(true);
                                } else {
                                    key.setAdmin(false);
                                }
                                key.setLockVersion(gson.toJson(kensBean_kejixia.get(i).getLock_version()));
                                key.setLockName(kensBean_kejixia.get(i).getLock_name());
                                key.setLockMac(kensBean_kejixia.get(i).getLock_mac());
                                key.setAdminPs(kensBean_kejixia.get(i).getAdminPwd());
                                key.setUnlockKey(kensBean_kejixia.get(i).getLock_key());
                                key.setAdminKeyboardPwd(kensBean_kejixia.get(i).getNoKeyPwd());
                                key.setDeletePwd(kensBean_kejixia.get(i).getDeletePwd());
                                key.setPwdInfo("");
                                key.setTimestamp(0);
                                key.setAesKeystr(kensBean_kejixia.get(i).getAesKeyStr());
                                // key.setTimezoneRawOffset(TimeZone.getDefault().getOffset(currentTimeMillis()));
                                key.setTimezoneRawOffset(Integer.parseInt(get(getActivity(), null, SPContants.SHIQU, "") + ""));

                                //上面是开锁用到的必要数据，下面这些是一些操作数据
                                key.setLockId(kensBean_kejixia.get(i).getLock_id());
                                key.setKeyId(kensBean_kejixia.get(i).getKey_id());
                                key.setLockAlias(kensBean_kejixia.get(i).getLock_alias());
                                key.setStartDate(parseLong(kensBean_kejixia.get(i).getStart()));
                                key.setEndDate(parseLong(kensBean_kejixia.get(i).getEnd()));

                                key.setUser_type(kensBean_kejixia.get(i).getUser_type());
                                key.setStatus(kensBean_kejixia.get(i).getStatus());
                                key.setPush(kensBean_kejixia.get(i).getPush());
                                key.setHouse_no(kensBean_kejixia.get(i).getHouse_no());
                                key.setTypes(kensBean_kejixia.get(i).getType());
                                key.setKeyStatus(kensBean_kejixia.get(i).getKeyStatus());
                                key.setBattery(kensBean_kejixia.get(i).getPower());
                                key.setLock_type(kensBean_kejixia.get(i).getLock_type());
                                key.setHas_valid_rent(kensBean_kejixia.get(i).getHas_valid_rent());
                                key.setReset_rent_pass(kensBean_kejixia.get(i).getReset_rent_pass());
                                key.setId(keyDao.insert(key));
                                keys_kejixia.add(key);
                            }

                        }
                        //清空本地并重新保存数据
                        DbService.saveKeyList(keys_kejixia);

                        kejiAdapter = new KeyTwoAdapter(getActivity(), keys_kejixia);
                        xlistview_kejixia.setAdapter(kejiAdapter);
                        kejiAdapter.notifyDataSetChanged();

                        //判断锁钥匙状态是否正常   110401 正常使用  110402 待接受  110405 	已冻结  110408 	已删除  110410 	已重置


                        //解绑锁的数据，如果没有网，上传没成功，存在本地；如果上传成功了   就删除
                        String jKeyid = get(getActivity(), null, SPContants.J_KEYID, "") + "";
                        String jLockid = get(getActivity(), null, SPContants.J_LOCKID, "") + "";
                        String aesKeyStr = get(getActivity(), null, SPContants.AESKEYSTR, "") + "";
                        for (int j = 0; j < kensBean_kejixia.size(); j++) {
                            String s1 = kensBean_kejixia.get(j).getLock_id();
                            String s2 = kensBean_kejixia.get(j).getKey_id();
                            String s3 = kensBean_kejixia.get(j).getAesKeyStr();
                            if (s1.equals(jLockid) && s2.equals(jKeyid) && s3.equals(aesKeyStr)) {
                                sid=SPUtils.get(MyApplcation.ctx,null,SPContants.LOCK_SESSION,"")+"";
                                if ("".equals(sid)){
                                    userPresenter.unbindLock(uid, jLockid, jKeyid, "");
                                }else {
                                    userPresenter.unbindLock(sid, jLockid, jKeyid, "");
                                }

                            }
                        }
                    } else {
                        liner_nokey_kejixia.setVisibility(View.VISIBLE);
                        xlistview_kejixia.setVisibility(View.GONE);
                    }
                }

            } else if (entity.getEventType() == KeyPresenter.mykeys_fail) {
                if (entity.getData() instanceof ServerError||entity.getData() instanceof TimeoutError){//服务器失败
                  //切换 锁备用服务器
                   showAlert();
                }else {
                    ByAlert.alert(entity.getMsg());
                }

            }
            // 解除绑定
            else if (entity.getEventType() == UserPresenter.unbindAdmin_success) {
                SaveKeyBean.saveDataTwo("2", null);

                ByAlert.alert(entity.getData());
                String accessToken = MyPreference.getStr(mContext, MyPreference.ACCESS_TOKEN);
                Key localKey = DbService.getKeyByAccessTokenAndLockmac(accessToken, jiebangKey);
                //删除本地钥匙(不删除本地钥匙，会导致下次绑定同一锁时导致无效)
                DbService.deleteKey(localKey);
                sid=SPUtils.get(MyApplcation.ctx,null,SPContants.LOCK_SESSION,"")+"";
                isLock= (boolean) SPUtils.get(MyApplcation.ctx,null,SPContants.ISLOCK,false);
                cz=2;
                if ("".equals(sid)){
                    keyPresenter.myKey(uid, "",isLock);
                }else {
                    keyPresenter.myKey(sid, "",isLock);
                }
//                Iterator<Key> iterator = keys.iterator();
//                while (iterator.hasNext()) {
//                    Key bean = iterator.next();
//                    if (deKeyId.equals(bean.getKeyId())) {
//                        iterator.remove();
//                        adapter.notifyDataSetChanged();
//                        break;
//                    }
//                }
            } else if (entity.getEventType() == UserPresenter.unbindAdmin_fail) {
                Log.d("unbind===",entity.getMsg()+"unbindAdmin_fail");
                if (entity.getData() instanceof ServerError||entity.getData() instanceof TimeoutError){//服务器失败
                    //切换 锁备用服务器
                    showAlert();
                }else {
                    ByAlert.alert(entity.getMsg());
                }

            } else if (entity.getEventType() == UserPresenter.uploadjilu_success) {//上传记录的地方，在开锁后上传开锁记录
                SPUtils.put(MyApplcation.ctx, null, SPContants.RECORDS, "");//上传成功之后清空掉操作日志
                SPUtils.put(MyApplcation.ctx, null, SPContants.RECORDS_LOCKID, "");
            } else if (entity.getEventType() == UserPresenter.uploadjilu_fail) {
                if (entity.getData() instanceof ServerError||entity.getData() instanceof TimeoutError){//服务器失败
                    //切换 锁备用服务器
                    showAlert();
                }else {
                    ByAlert.alert(entity.getMsg());
                }

            } else if (entity.getEventType() == UserPresenter.dianliang_success) { // 低电量
            } else if (entity.getEventType() == UserPresenter.dianliang_fail) {
                Log.d("unbind===",entity.getMsg()+"dianliang_fail");

            } else if (entity.getEventType() == UserPresenter.openid_success) {
                Log.d("unbind===",entity.getData().toString()+"openid_success");
                OpenIdBean b = (OpenIdBean) entity.getData();
                SPUtils.put(getActivity(), null, SPContants.OPENID, b.getOpenid());
            } else if (entity.getEventType() == UserPresenter.openid_fail) {
                Log.d("unbind===",entity.getMsg()+"openid_fail");
            }else
            if (entity.getEventType() == KeyPresenter.downBeifen_success) {//下载备份钥匙（解决v2绑定之后  用v3解绑管理员造成的数据不存在问题）
                beifenBean = (DownBeifenBean) entity.getData();
                KeyFragment.bleSession.setOperation(Operation.RESET_LOCK);
                KeyFragment.bleSession.setLockmac(beifenBean.getLockMac());
                jiebangKey = beifenBean.getLockMac();
            }else
            if (entity.getEventType() == KeyPresenter.downBeifen_fail) {
                Log.d("unbind===",entity.getMsg()+"downBeifen_fail");
                ByAlert.alert(entity.getData());
            }
            // 解除绑定
            else if (entity.getEventType() == KeyTwoPresenter.unbindAdmin_success) {

                SaveKeyBean.saveDataTwo("2", null);
                ByAlert.alert(entity.getData());
                String accessToken = MyPreference.getStr(mContext, MyPreference.ACCESS_TOKEN);
                Key localKey = DbService.getKeyByAccessTokenAndLockmac(accessToken, jiebangKey);
                //删除本地钥匙(不删除本地钥匙，会导致下次绑定同一锁时导致无效)
                DbService.deleteKey(localKey);

                Iterator<Key> iterator = keys.iterator();
                while (iterator.hasNext()) {
                    Key bean = iterator.next();
                    if (deKeyId.equals(bean.getKeyId())) {
                        iterator.remove();
                        adapter.notifyDataSetChanged();
                        break;
                    }
                }
            } else if (entity.getEventType() == KeyTwoPresenter.unbindAdmin_fail) {
                Log.d("unbind===",entity.getMsg()+"unbindAdmin_fail");
                if (entity.getData() instanceof ServerError||entity.getData() instanceof TimeoutError){//服务器失败
                    //切换 锁备用服务器
                    showAlert();
                }else {
                    ByAlert.alert(entity.getMsg());
                }
            }
            else if (entity.getEventType() == KeyTwoPresenter.myKey_success){//获取白马锁列表
                li_search.setVisibility(View.GONE);
                kensBean_baima = (List<KeysBean>) entity.getData();
                Log.d("=====keji==",kensBean_baima.toString());

                if (kensBean_baima.size()>0){
                    clockProduct=2;
                    initClock();
                }
                if (kensBean_baima != null) {
                    if (kensBean_baima.size() > 0) {
                        keys.clear();
//                        //清空本地并重新保存数据
//                        DbService.deleteAllKey();
                        for (int i = 0; i < kensBean_baima.size(); i++) {
                            xlistview.setVisibility(View.VISIBLE);
                            liner_nokey.setVisibility(View.GONE);
                            Key key = new Key();
                            key.setAccessToken(MyPreference.getStr(mContext,
                                    MyPreference.ACCESS_TOKEN));
                            if (kensBean_baima.get(i).getType().equals("0")) {
                                key.setAdmin(true);
                            } else {
                                key.setAdmin(false);
                            }
                            //  key.setLockVersion(gson.toJson(kensBean.get(i).getLock_version()));
                            key.setLockName(kensBean_baima.get(i).getLock_name());
                            key.setLockMac(kensBean_baima.get(i).getLock_mac());
                            key.setAdminPs(kensBean_baima.get(i).getAdminPwd());
                            key.setUnlockKey(kensBean_baima.get(i).getLock_key());
                            key.setAdminKeyboardPwd(kensBean_baima.get(i).getNoKeyPwd());
                            key.setDeletePwd(kensBean_baima.get(i).getDeletePwd());
                            key.setPwdInfo("");
                            key.setTimestamp(0);
                            key.setAesKeystr(kensBean_baima.get(i).getAesKeyStr());
                            // key.setTimezoneRawOffset(TimeZone.getDefault().getOffset(currentTimeMillis()));
                            key.setTimezoneRawOffset(Integer.parseInt(get(getActivity(), null, SPContants.SHIQU, "") + ""));

                            //上面是开锁用到的必要数据，下面这些是一些操作数据
                            key.setLockId(kensBean_baima.get(i).getLock_id());
                            key.setKeyId(kensBean_baima.get(i).getKey_id());
                            key.setLockAlias(kensBean_baima.get(i).getLock_alias());
                            key.setStartDate(parseLong(kensBean_baima.get(i).getStart()));
                            key.setEndDate(parseLong(kensBean_baima.get(i).getEnd()));

                            key.setUser_type(kensBean_baima.get(i).getUser_type());
                            key.setStatus(kensBean_baima.get(i).getStatus());
                            key.setPush(kensBean_baima.get(i).getPush());
                            key.setHouse_no(kensBean_baima.get(i).getHouse_no());
                            key.setTypes(kensBean_baima.get(i).getType());
                            key.setKeyStatus(kensBean_baima.get(i).getKeyStatus());
                            key.setBattery(kensBean_baima.get(i).getPower());
                            key.setLock_type(kensBean_baima.get(i).getLock_type());
                            key.setHas_valid_rent(kensBean_baima.get(i).getHas_valid_rent());
                            key.setReset_rent_pass(kensBean_baima.get(i).getReset_rent_pass());
//                            key.setId(keyDao.insert(key));
                            keys.add(key);
                        }
//                        //清空本地并重新保存数据
//                        DbService.saveKeyList(keys);

                        adapter = new KeyTwoAdapter(getActivity(), keys);
                        xlistview.setAdapter(adapter);
                        adapter.notifyDataSetChanged();

//                        //解绑锁的数据，如果没有网，上传没成功，存在本地；如果上传成功了   就删除
//                        String jKeyid = get(getActivity(), null, SPContants.J_KEYID, "") + "";
//                        String jLockid = get(getActivity(), null, SPContants.J_LOCKID, "") + "";
//                        String aesKeyStr = get(getActivity(), null, SPContants.AESKEYSTR, "") + "";
//                        for (int j = 0; j < kensBean_baima.size(); j++) {
//                            String s1 = kensBean_baima.get(j).getLock_id();
//                            String s2 = kensBean_baima.get(j).getKey_id();
//                            String s3 = kensBean_baima.get(j).getAesKeyStr();
//                            if (s1.equals(jLockid) && s2.equals(jKeyid) && s3.equals(aesKeyStr)) {
//                                userPresenter.unbindLock(uid, jLockid, jKeyid, "");
//                            }
//                        }
                    } else {
                        liner_nokey.setVisibility(View.VISIBLE);
                        xlistview.setVisibility(View.GONE);
                    }
                }

            }else if (entity.getEventType() == KeyTwoPresenter.myKey_fail){
                Log.d("unbind===",entity.getMsg()+"myKey_fail");
                if (entity.getData() instanceof ServerError||entity.getData() instanceof TimeoutError){//服务器失败
                    //切换 锁备用服务器
                    showAlert();
                }else {
                    ByAlert.alert(entity.getMsg());
                }
            } else if (entity.getEventType()==UserPresenter.BY_ScienerV3_addIcCard_success){//添加ic卡
                ByAlert.alert("ic卡添加成功");
            }else if (entity.getEventType()==UserPresenter.BY_ScienerV3_addIcCard_fail){
                Log.d("unbind===",entity.getMsg()+"BY_ScienerV3_addIcCard_fail");

            }else if (entity.getEventType()==UserPresenter.BY_ScienerV3_delIcCard_success){
                //发送删除ic卡成功的广播
                getActivity().sendBroadcast(new Intent(BleConstant.DELETE_ICCARD));

            }else if (entity.getEventType()==UserPresenter.BY_ScienerV3_delIcCard_fail){
                Log.d("unbind===",entity.getMsg()+"BY_ScienerV3_delIcCard_fail");
                ByAlert.alert(entity.getMsg());

            }else if (entity.getEventType()==UserPresenter.BY_ScienerV3_clearIcCard_success){
                //发送删除ic卡列表的广播
                getActivity().sendBroadcast(new Intent(BleConstant.CLEAR_ICCARD));

            }else if (entity.getEventType()==UserPresenter.BY_ScienerV3_clearIcCard_fail){
                Log.d("unbind===",entity.getMsg()+"BY_ScienerV3_clearIcCard_fail");
                ByAlert.alert(entity.getMsg());
            }else if (entity.getEventType()==UserPresenter.By_GETSID_success){//获取sid 成功
                SIDBean data1 = (SIDBean) entity.getData();
                SPUtils.put(MyApplcation.ctx,null, SPContants.LOCK_SESSION,data1.getSid());
                SPUtils.put(MyApplcation.ctx,null,SPContants.ISLOCK,true);
                toRefreshData(data1.getSid());
            }else if (entity.getEventType()==UserPresenter.By_GETSID_fail){
                ByAlert.alert(entity.getMsg());
            }
        }

    }


    /**
     * 通通锁回调
     */
    public TTLockCallback mTTLockCallback = new TTLockCallback() {
        long cardno;
        @Override
        public void onFoundDevice(ExtendedBluetoothDevice extendedBluetoothDevice) {
            Log.d("=====tt","onFoundDevice()"+extendedBluetoothDevice.toString());
            //发现设备并广播
            broadcastUpdate(BleConstant.ACTION_BLE_DEVICE, BleConstant.DEVICE, extendedBluetoothDevice);
            String accessToken = MyPreference.getStr(mContext, MyPreference.ACCESS_TOKEN);
            Key localKey = DbService.getKeyByAccessTokenAndLockmac(accessToken, extendedBluetoothDevice.getAddress());
            if (localKey != null) {
                switch (bleSession.getOperation()) {
                    case UNLOCK:


//                        if(extendedBluetoothDevice.isTouch()){}
//                            mTTLockAPI.connect(extendedBluetoothDevice);
                        break;
                    case SET_ADMIN_KEYBOARD_PASSWORD:
                        break;
                    case SET_DELETE_PASSWORD:
                        break;
                    case SET_LOCK_TIME:
                        if (extendedBluetoothDevice.getAddress().equals(bleSession.getLockmac()))
                            mTTLockAPI.connect(extendedBluetoothDevice);
                        break;
                    case RESET_KEYBOARD_PASSWORD:
                        if (ActivityYongHu.addLock) {
                            ActivityYongHu.addLock = false;
                            mTTLockAPI.connect(extendedBluetoothDevice);
                        }
                        break;
                    case RESET_EKEY:
                    case RESET_LOCK:

                        mTTLockAPI.connect(extendedBluetoothDevice);
                        break;
                    case GET_LOCK_TIME:
                    case GET_OPERATE_LOG:
                        if (extendedBluetoothDevice.getAddress().equals(bleSession.getLockmac()))
                            mTTLockAPI.connect(extendedBluetoothDevice);
                        break;
                }
            }
        }

        @Override
        public void onDeviceConnected(ExtendedBluetoothDevice extendedBluetoothDevice) {
//            Log.d("=====tt","onDeviceConnected()");

            LogUtil.d("bleSession.getOperation():" + bleSession.getOperation(), DBG);
            String accessToken = MyPreference.getStr(mContext, MyPreference.ACCESS_TOKEN);
            //TODO:
            Key localKey = DbService.getKeyByAccessTokenAndLockmac(accessToken, extendedBluetoothDevice.getAddress());
            String openid = String.valueOf(SPUtils.get(getActivity(), null, SPContants.OPENID, ""));
            int id = openid == null || openid.equals("") ? Integer.parseInt(SPUtils.get(getActivity(), null, SPContants.USER_ID, "") + "") : Integer.parseInt(SPUtils.get(getActivity(), null, SPContants.OPENID, "") + "");
            curKey = curKeys;
            operateSuccess = false;
            switch (bleSession.getOperation()) {
                case ADD_ADMIN:
                    //TODO:判断本地是否存在
                    mTTLockAPI.addAdministrator(extendedBluetoothDevice);
                    break;
                case UNLOCK:
                case CLICK_UNLOCK:
                    if (localKey != null) {//本地存在锁
                        if (localKey.isAdmin())
                            mTTLockAPI.unlockByAdministrator(extendedBluetoothDevice, id, localKey.getLockVersion(), localKey.getAdminPs(), localKey.getUnlockKey(), localKey.getLockFlagPos(), currentTimeMillis(), localKey.getAesKeystr(), localKey.getTimezoneRawOffset());
                        else
                            mTTLockAPI.unlockByUser(extendedBluetoothDevice, id, localKey.getLockVersion(), localKey.getStartDate() * 1000, localKey.getEndDate() * 1000, localKey.getUnlockKey(), localKey.getLockFlagPos(), localKey.getAesKeystr(), localKey.getTimezoneRawOffset());
                    }
                    break;
                case SET_ADMIN_KEYBOARD_PASSWORD://管理码
                    mTTLockAPI.setAdminKeyboardPassword(extendedBluetoothDevice, id, curKey.getLockVersion(), curKey.getAdminPs(), curKey.getUnlockKey(), curKey.getLockFlagPos(), curKey.getAesKeystr(), bleSession.getPassword());
                    break;
                case SET_DELETE_PASSWORD://删除码
                    mTTLockAPI.setDeletePassword(extendedBluetoothDevice, id, curKey.getLockVersion(), curKey.getAdminPs(), curKey.getUnlockKey(), curKey.getLockFlagPos(), curKey.getAesKeystr(), bleSession.getPassword());
                    break;
                case SET_LOCK_TIME://设置锁时间
                    mTTLockAPI.setLockTime(extendedBluetoothDevice, id, curKey.getLockVersion(), curKey.getUnlockKey(), currentTimeMillis(), curKey.getLockFlagPos(), curKey.getAesKeystr(), localKey.getTimezoneRawOffset());
                    break;
                case RESET_KEYBOARD_PASSWORD://重置键盘密码
                    mTTLockAPI.resetKeyboardPassword(extendedBluetoothDevice, id, curKey.getLockVersion(), curKey.getAdminPs(), curKey.getUnlockKey(), curKey.getLockFlagPos(), curKey.getAesKeystr());
                    break;
                case RESET_EKEY://重置电子钥匙 锁标志位+1
                    mTTLockAPI.resetEKey(extendedBluetoothDevice, id, curKey.getLockVersion(), curKey.getAdminPs(), curKey.getLockFlagPos() + 1, curKey.getAesKeystr());
                    break;
                case RESET_LOCK://重置锁
//                    if (keysChangAn.getAdminPs() == null || keysChangAn.getAdminPs().equals("") || keysChangAn.getUnlockKey() == null || keysChangAn.getUnlockKey().equals("")) {
//                        mTTLockAPI.resetLock(extendedBluetoothDevice, id, gson.toJson(beifenBean.getLockVersion()), beifenBean.getAdminPs(), keysChangAn.getUnlockKey(), beifenBean.getLockFlagPos() + 1, beifenBean.getAesKeyStr());
//                    } else {
//                        mTTLockAPI.resetLock(extendedBluetoothDevice, id, keysChangAn.getLockVersion(), keysChangAn.getAdminPs(), keysChangAn.getUnlockKey(), keysChangAn.getLockFlagPos() + 1, keysChangAn.getAesKeystr());
//
//                    }

                    mTTLockAPI.resetLock(extendedBluetoothDevice, id, keysChangAn.getLockVersion(), keysChangAn.getAdminPs(), keysChangAn.getUnlockKey(), keysChangAn.getLockFlagPos() + 1, keysChangAn.getAesKeystr());

                    break;
                case GET_OPERATE_LOG://获取操作日志
                    mTTLockAPI.getOperateLog(extendedBluetoothDevice, curKey.getLockVersion(), curKey.getAesKeystr(), curKey.getTimezoneRawOffset());
                    break;
                case GET_LOCK_TIME://获取锁时间
                    mTTLockAPI.getLockTime(extendedBluetoothDevice, curKey.getLockVersion(), curKey.getAesKeystr(), curKey.getTimezoneRawOffset());
                    break;
                case LOCKCAR_UP://车位锁升
                    if (localKey.isAdmin())
                        mTTLockAPI.lockByAdministrator(extendedBluetoothDevice, 0, localKey.getLockVersion(), localKey.getAdminPs(), localKey.getUnlockKey(), localKey.getLockFlagPos(), localKey.getAesKeystr());
                    else
                        mTTLockAPI.lockByUser(extendedBluetoothDevice, 0, localKey.getLockVersion(), localKey.getStartDate(), localKey.getEndDate(), localKey.getUnlockKey(), localKey.getLockFlagPos(), localKey.getAesKeystr(), localKey.getTimezoneRawOffset());
//                    mTTLockAPI.lockByUser(extendedBluetoothDevice, 0, localKey.getLockVersion(), 1489990922165l, 1490077322165l, localKey.getUnlockKey(), localKey.getLockFlagPos(), localKey.getAesKeystr(), localKey.getTimezoneRawOffset());
                    break;
                case LOCKCAR_DOWN://车位锁降
                    if (localKey.isAdmin())
                        mTTLockAPI.unlockByAdministrator(extendedBluetoothDevice, 0, localKey.getLockVersion(), localKey.getAdminPs(), localKey.getUnlockKey(), localKey.getLockFlagPos(), currentTimeMillis(), localKey.getAesKeystr(), localKey.getTimezoneRawOffset());
                    else
                        mTTLockAPI.unlockByUser(extendedBluetoothDevice, 0, localKey.getLockVersion(), localKey.getStartDate(), localKey.getEndDate(), localKey.getUnlockKey(), localKey.getLockFlagPos(), localKey.getAesKeystr(), localKey.getTimezoneRawOffset());
//                    mTTLockAPI.unlockByUser(extendedBluetoothDevice, 0, localKey.getLockVersion(), 1489990922165l, 1490077322165l, localKey.getUnlockKey(), localKey.getLockFlagPos(), localKey.getAesKeystr(), localKey.getTimezoneRawOffset());
                    break;
                case DELETE_ONE_KEYBOARDPASSWORD://这里的密码类型传0
                    mTTLockAPI.deleteOneKeyboardPassword(extendedBluetoothDevice, 0, localKey.getLockVersion(), localKey.getAdminPs(), localKey.getUnlockKey(), localKey.getLockFlagPos(), 0, bleSession.getPassword(), localKey.getAesKeystr());
                    break;
                case ADDICCARD://添加ic卡
                    Log.d("====iccard=","isture");
                    mTTLockAPI.addICCard(extendedBluetoothDevice,
                            0,
                            ActivityAddICCard.localKey.getLockVersion(),
                            ActivityAddICCard.localKey.getAdminPs(),
                            ActivityAddICCard.localKey.getUnlockKey(),
                            ActivityAddICCard.localKey.getLockFlagPos(),
                            ActivityAddICCard.localKey.getAesKeystr());
                    break;

                case DELETEICCARD:

                    mTTLockAPI.deleteICCard(extendedBluetoothDevice,
                            0,
                            ActivityICCardList.localKey.getLockVersion(),
                            ActivityICCardList.localKey.getAdminPs(),
                            ActivityICCardList.localKey.getUnlockKey(),
                            ActivityICCardList.localKey.getLockFlagPos(),
                            Long.parseLong(ActivityICCardList.cardNo),
                            ActivityICCardList.localKey.getAesKeystr());
                    break;

                case CLEARICCARD:
                    mTTLockAPI.clearICCard(extendedBluetoothDevice,
                            0,
                            ActivityICCardList.localKey.getLockVersion(),
                            ActivityICCardList.localKey.getAdminPs(),
                            ActivityICCardList.localKey.getUnlockKey(),
                            ActivityICCardList.localKey.getLockFlagPos(),
                            ActivityICCardList.localKey.getAesKeystr());
                    break;

                case DOUNLOCK:

                    if (ActivityGuanLiKey.localKey.getUser_type().equals("0")){//管理员开锁
                        mTTLockAPI.unlockByAdministrator(null,
                                openid==null||openid.equals("")?Integer.parseInt(SPUtils.get(getActivity(), null, SPContants.USER_ID, "") + ""):Integer.parseInt(SPUtils.get(getActivity(), null, SPContants.OPENID, "") + ""),
                                ActivityGuanLiKey.localKey.getLockVersion(),
                                ActivityGuanLiKey.localKey.getAdminPs(),
                                ActivityGuanLiKey.localKey.getUnlockKey(),
                                ActivityGuanLiKey.localKey.getLockFlagPos(),
                                System.currentTimeMillis(),
                                ActivityGuanLiKey.localKey.getAesKeystr(),
                                ActivityGuanLiKey.localKey.getTimezoneRawOffset());
                    }else {//租客开锁

                    mTTLockAPI.unlockByUser(null,
                            openid == null || openid.equals("") ? Integer.parseInt(SPUtils.get(getActivity(), null, SPContants.USER_ID, "") + "") : Integer.parseInt(SPUtils.get(getActivity(), null, SPContants.OPENID, "") + ""),
                            ActivityGuanLiKey.localKey.getLockVersion(),
                            ActivityGuanLiKey.localKey.getStartDate()*1000,
                            ActivityGuanLiKey.localKey.getEndDate()*1000,
                            ActivityGuanLiKey.localKey.getUnlockKey(),
                            ActivityGuanLiKey.localKey.getLockFlagPos(),
                            ActivityGuanLiKey.localKey.getAesKeystr(),
                            ActivityGuanLiKey.localKey.getTimezoneRawOffset());
                    }

                    break;

                case DEVICETIME: //获取锁时间
                    mTTLockAPI.getLockTime(extendedBluetoothDevice,ActivityGuanLiKey.localKey.getLockVersion(),ActivityGuanLiKey.localKey.getAesKeystr(),
                            ActivityGuanLiKey.localKey.getTimezoneRawOffset());
                    break;

                case CHECKDEVICETIME: //设置锁时间

                    long oldServiceTime = (long) get(getActivity(), null, SPContants.oldServiceTime, 0l);
                    long oldPhoneTime = (long) get(getActivity(), null, SPContants.oldPhoneTime, 0l);
                    long times = System.currentTimeMillis()-oldPhoneTime+oldServiceTime;
//                    long times = TTLockTimeTest.dateTimes;
                    Log.d("====onSetLockTime=",times+"");
                    mTTLockAPI.setLockTime(extendedBluetoothDevice,
                            id,
                            ActivityGuanLiKey.localKey.getLockVersion(),
                            ActivityGuanLiKey.localKey.getUnlockKey(),
                            times,
                            ActivityGuanLiKey.localKey.getLockFlagPos(),
                            ActivityGuanLiKey.localKey.getAesKeystr(),
                            ActivityGuanLiKey.localKey.getTimezoneRawOffset());

                    break;

//                case SEARCHICCARD://查询ic卡
//                    mTTLockAPI.searchDeviceFeature(extendedBluetoothDevice,0, ActivityICCardList.localKey.getLockVersion(),
//                            ActivityICCardList.localKey.getAdminPs(),ActivityICCardList.localKey.getUnlockKey(),
//                            ActivityICCardList.localKey.getLockFlagPos(),ActivityICCardList.localKey.getAesKeystr());
//                    break;

            }
        }

        @Override
        public void onDeviceDisconnected( final ExtendedBluetoothDevice extendedBluetoothDevice) {
            diconectNum++;
            //默认是开门标志
            Log.d("====iccard=","onDeviceDisconnected()");

            if(!operateSuccess){ //设备未连接
                if (diconectNum<2) {
                    //重连一次
                    mTTLockAPI.connect(extendedBluetoothDevice);
                } else {
                    //断开连接
                    broadcastUpdate(BleConstant.ACTION_BLE_DISCONNECTED, BleConstant.DEVICE, extendedBluetoothDevice);
                    diconectNum=0;
                }
            }else {
                    //断开连接
                    broadcastUpdate(BleConstant.ACTION_BLE_DISCONNECTED, BleConstant.DEVICE, extendedBluetoothDevice);

            }


            try {
                ((BaseOtherActivity) curActivity).closeProgressDialog();
            } catch (Exception e) {

            }
        }

        @Override
        public void onGetLockVersion(ExtendedBluetoothDevice extendedBluetoothDevice, int i, int i1, int i2, int i3, int i4, Error error) {

        }

        @Override
        public void onAddAdministrator( ExtendedBluetoothDevice extendedBluetoothDevice,
                                         String lockVersionString,
                                         String adminPs,
                                         String unlockKey,
                                         String adminKeyboardPwd,
                                         String deletePwd,
                                         String pwdInfo,
                                         long timestamp,
                                         String aesKeystr,
                                         int feature,
                                        String modelNumber,
                                        String hardwareRevision,
                                        String firmwareRevision, Error error) {
            Log.d("=====tt","onAddAdministrator()");
            Log.d("onAddAdministrator","添加管理员:" + error + "," + "lockVersion--->" + lockVersionString + "电量------>" + extendedBluetoothDevice.getBatteryCapacity());
            operateSuccess = true;

            if (error == Error.SUCCESS) {
//                curActivity.finish();
                //TODO:save数据
                Intent intent = new Intent(BleConstant.ADD_ADMIN);
                intent.putExtra("extendedBluetoothDevice",extendedBluetoothDevice);
                intent.putExtra("lockVersionString",lockVersionString);
                intent.putExtra("adminPs",adminPs);
                intent.putExtra("unlockKey",unlockKey);
                intent.putExtra("adminKeyboardPwd",adminKeyboardPwd);
                intent.putExtra("deletePwd",deletePwd);
                intent.putExtra("pwdInfo",pwdInfo);
                intent.putExtra("timestamp",timestamp);
                intent.putExtra("aesKeystr",aesKeystr);
                intent.putExtra("feature",feature);
                intent.putExtra("modelNumber",modelNumber);
                intent.putExtra("hardwareRevision",hardwareRevision);
                intent.putExtra("firmwareRevision",firmwareRevision);
                MyApplcation.ctx.sendBroadcast(intent);

//                final Key key = new Key();
//                key.setAccessToken(MyPreference.getStr(mContext, MyPreference.ACCESS_TOKEN));
//                key.setAdmin(true);
//                key.setLockVersion(lockVersionString);
//                key.setLockName(extendedBluetoothDevice.getName());
//                key.setLockMac(extendedBluetoothDevice.getAddress());
//                key.setAdminPs(adminPs);
//                key.setUnlockKey(unlockKey);
//                key.setAdminKeyboardPwd(adminKeyboardPwd);
//                key.setDeletePwd(deletePwd);
//                key.setPwdInfo(pwdInfo);
//                key.setTimestamp(timestamp);
//                key.setAesKeystr(aesKeystr);
//                key.setSpecialValue(feature);
//                key.setBattery(extendedBluetoothDevice.getBatteryCapacity());
//
////                key.setLockAlias(ActivitySheBei.alisa);
//                //获取当前时区偏移量 可以传入-1 不考虑时区问题
//                key.setTimezoneRawOffset(TimeZone.getDefault().getOffset(System.currentTimeMillis()));
//                key.setModelNumber(modelNumber);
//                key.setHardwareRevision(hardwareRevision);
//                key.setFirmwareRevision(firmwareRevision);
//                SaveKeyBean.saveData("1", key);
//                toast("锁添加成功，正在上传服务端进行初始化操作");
//                Log.d("addd===",ActivitySheBei.alisa);
//
//                keyPresenter.getAddMain(uid, "6323", ActivitySheBei.alisa,
//                        ActivitySheBei.alisa, extendedBluetoothDevice.getAddress(), unlockKey, "0",
//                        aesKeystr.toString(), lockVersionString.toString(), adminPs, adminKeyboardPwd, deletePwd,
//                        pwdInfo, timestamp + "", feature + "",
//                        extendedBluetoothDevice.getBatteryCapacity());
            } else {//失败
                toast(error.getErrorMsg());
            }


        }

        @Override
        public void onResetEKey(ExtendedBluetoothDevice extendedBluetoothDevice, final int lockFlagPos, Error error) {
            operateSuccess = true;
            Log.d("=====tt","onResetEKey()");
            if (error == Error.SUCCESS) {

                curKey.setLockFlagPos(lockFlagPos);
                DbService.updateKey(curKey);
                toast("重置电子钥匙成功，锁标志位:" + lockFlagPos);

            } else
                toast(error.getErrorMsg());
            ((BaseOtherActivity) MyApplcation.curActivity).closeProgressDialog();
        }

        @Override
        public void onSetLockName(ExtendedBluetoothDevice extendedBluetoothDevice, String s, Error error) {

        }

        @Override
        public void onSetAdminKeyboardPassword(ExtendedBluetoothDevice extendedBluetoothDevice, String adminCode, Error error) {
            operateSuccess = true;
            if (error == Error.SUCCESS) {

                curKey.setAdminKeyboardPwd(adminCode);
                DbService.updateKey(curKey);
                toast("设置管理码成功:" + adminCode);
            } else toast(error.getErrorMsg());
            ((BaseOtherActivity) MyApplcation.curActivity).closeProgressDialog();
        }

        @Override
        public void onSetDeletePassword(ExtendedBluetoothDevice extendedBluetoothDevice, String deleteCode, Error error) {
            operateSuccess = true;
            if (error == Error.SUCCESS) {

                curKey.setDeletePwd(deleteCode);
                DbService.updateKey(curKey);
                toast("设置清空码成功:" + deleteCode);
            } else toast(error.getErrorMsg());
            ((BaseOtherActivity) MyApplcation.curActivity).closeProgressDialog();
        }

        @Override
        public void onUnlock(ExtendedBluetoothDevice extendedBluetoothDevice, int uid, int uniqueid, long lockTime, Error error) {
            Log.d("====iccard=","onUnlock==error"+extendedBluetoothDevice.toString());
            operateSuccess = true;
            if (error == Error.SUCCESS) {
                //设置锁时间
                int shiqu = curKey.getTimezoneRawOffset();
                String uids = get(getActivity(), null, SPContants.USER_ID, "") + "";
                String time = get(getActivity(), null, SPContants.SHICHA, "") + "";
                long oldServiceTime = (long) get(getActivity(), null, SPContants.oldServiceTime, 0l);
                long oldPhoneTime = (long) get(getActivity(), null, SPContants.oldPhoneTime, 0l);
                long times = System.currentTimeMillis()-oldPhoneTime+oldServiceTime;
                Log.d("===settime",oldPhoneTime+"=="+oldServiceTime);

                mTTLockAPI.setLockTime(extendedBluetoothDevice,
                        0,
                        curKey.getLockVersion(),
                        curKey.getUnlockKey(),
                        times,
                        curKey.getLockFlagPos(),
                        curKey.getAesKeystr(),
                        curKey.getTimezoneRawOffset());
            } else toast(error.getErrorMsg());
            ((BaseOtherActivity) MyApplcation.curActivity).closeProgressDialog();
            try {
                closeProgressDialog();
            } catch (Exception e) {
            }
        }

        @Override
        public void onLock(ExtendedBluetoothDevice extendedBluetoothDevice, int uniqueid, Error error) {
            Log.d("====iccard=","onLock==自动关锁error");
            operateSuccess = true;
            if (error == Error.SUCCESS) {

                toast("关锁成功");
            } else toast(error.getErrorMsg());
            ((BaseOtherActivity) MyApplcation.curActivity).closeProgressDialog();
        }

        @Override
        public void onSetLockTime(ExtendedBluetoothDevice extendedBluetoothDevice, Error error) {
            Log.d("====onSetLockTime=","onSetLockTime==设置锁时间error=="+error.toString());
            operateSuccess = true;
            if (error == Error.SUCCESS) {
                //   toast("设置锁时间成功");
                //获取操作日志
                switch (bleSession.getOperation()) {
                    case ADDICCARD: //设置带有时间限制的ic卡 添加iccard
                        userPresenter.addIcCard(uid,ActivityAddICCard.localKey.getLockId(),cardno+"",ActivityAddICCard.icCardName,ActivityAddICCard.startDate,ActivityAddICCard.endDate);
                        getActivity().sendBroadcast(new Intent(BleConstant.ADD_ICCARD));
                        break;
                    case DOUNLOCK: //开锁
                        mTTLockAPI.getOperateLog(extendedBluetoothDevice, curKey.getLockVersion(), curKey.getAesKeystr(), curKey.getTimezoneRawOffset());
                        break;

                    case CHECKDEVICETIME: //校验时间 成功
                        getActivity().sendBroadcast(new Intent(BleConstant.CHECKLOCKTIME));
                        break;
                }

            } else toast(error.getErrorMsg());
            ((BaseOtherActivity) MyApplcation.curActivity).closeProgressDialog();
        }

        @Override
        public void onGetLockTime(ExtendedBluetoothDevice extendedBluetoothDevice, long lockTime, Error error) {

            operateSuccess = true;
            if (error == Error.SUCCESS) {
                Log.d("===onGetLockTime",lockTime+"");
                Intent intent = new Intent(BleConstant.DEVICETIME);
                intent.putExtra("locktime",lockTime);
                getActivity().sendBroadcast(intent);
                //转换成锁时区时间
                //   String time = DateUitl.getTime(lockTime - TimeZone.getDefault().getOffset(System.currentTimeMillis()) + curKey.getTimezoneRawOffset(), "yyyy:MM:dd HH:mm");
                //     toast("当前锁时区时间:" + time);
            } else toast(error.getErrorMsg());
            ((BaseOtherActivity) MyApplcation.curActivity).closeProgressDialog();
        }

        @Override
        public void onResetKeyboardPassword(ExtendedBluetoothDevice extendedBluetoothDevice, final String pwdInfo, final long timestamp, final Error error) {
            operateSuccess = true;
            if (error == Error.SUCCESS) {

                toast("重码成功置键盘密");
                curKey.setPwdInfo(pwdInfo);
                curKey.setTimestamp(timestamp);
                DbService.updateKey(curKey);

                // 发送广播通知锁重置键盘密码成功
                Intent intent2 = new Intent("suo_ok");
                getActivity().sendBroadcast(intent2);
            } else {
                toast(error.getErrorMsg());
            }
            ((BaseOtherActivity) MyApplcation.curActivity).closeProgressDialog();
        }

        @Override
        public void onSetMaxNumberOfKeyboardPassword(ExtendedBluetoothDevice extendedBluetoothDevice, int i, Error error) {

        }

        @Override
        public void onResetKeyboardPasswordProgress(ExtendedBluetoothDevice extendedBluetoothDevice, int i, Error error) {

        }

        @Override
        public void onResetLock(ExtendedBluetoothDevice extendedBluetoothDevice, Error error) {
            Log.d("====iccard=","onResetLock==自动关锁error"+error);
            try {
                closeProgressDialog();
            } catch (Exception e) {
            }
            operateSuccess = true;
            if (error == Error.SUCCESS) {

                toast("锁重置成功，当前钥匙已失效");

                SaveKeyBean.saveDataTwo("1", keysChangAn);

                userPresenter.unbindLock(uid, lockKeyId, deKeyId, "");

            } else toast(error.getErrorMsg());

        }

        @Override
        public void onAddKeyboardPassword(ExtendedBluetoothDevice extendedBluetoothDevice, int i, String s, long l, long l1, Error error) {

        }

        @Override
        public void onModifyKeyboardPassword(ExtendedBluetoothDevice extendedBluetoothDevice, int i, String s, String s1, Error error) {

        }

        @Override
        public void onDeleteOneKeyboardPassword(ExtendedBluetoothDevice extendedBluetoothDevice, int keyboardPwdTypei, String deletedPwd, Error error) {
            if (error == Error.SUCCESS) {
                toast("通过蓝牙删除密码成功");
//                if(operateCallback != null)
//                    operateCallback.onSuccess();
            } else toast(error.getErrorMsg());
            ((BaseOtherActivity) MyApplcation.curActivity).closeProgressDialog();
        }

        @Override
        public void onDeleteAllKeyboardPassword(ExtendedBluetoothDevice extendedBluetoothDevice, Error error) {

        }

        @Override
        public void onGetOperateLog(ExtendedBluetoothDevice extendedBluetoothDevice, String records, Error error) {
            Log.d("====onSetLockTime=","onGetOperateLog==error"+error.toString());
            toast("门开了");
            operateSuccess = true;
            //开锁流程走完了后  发送门开广播
            getActivity().sendBroadcast(new Intent(BleConstant.UNLOCK));
            if (error == Error.SUCCESS) {
                //toast("操作日志:" + records);
                sid=SPUtils.get(MyApplcation.ctx,null,SPContants.LOCK_SESSION,"")+"";

                SPUtils.put(MyApplcation.ctx, null, SPContants.RECORDS, records);
                SPUtils.put(MyApplcation.ctx, null, SPContants.RECORDS_LOCKID, lockid);
                long oldServiceTime = (long) get(getActivity(), null, SPContants.oldServiceTime, 0l);
                long oldPhoneTime = (long) get(getActivity(), null, SPContants.oldPhoneTime, 0l);
                if ("".equals(sid)){
                    userPresenter.uploadHistoryOfUnlock(get(getActivity(), null, SPContants.USER_ID, "") + "", lockid, records, "1",(System.currentTimeMillis()-oldPhoneTime+oldServiceTime)/1000,extendedBluetoothDevice.getBatteryCapacity());//上传开锁记录

                }else {
                    userPresenter.uploadHistoryOfUnlock(sid, lockid, records, "1",(System.currentTimeMillis()-oldPhoneTime+oldServiceTime)/1000,extendedBluetoothDevice.getBatteryCapacity());//上传开锁记录

                }
                if (extendedBluetoothDevice.getBatteryCapacity() <= 20) {
                    userPresenter.updateDianLiang(get(getActivity(), null, SPContants.USER_ID, "") + "", lockid, String.valueOf(extendedBluetoothDevice.getBatteryCapacity()));//低电量
                }

            } else toast(error.getErrorMsg());
            ((BaseOtherActivity) MyApplcation.curActivity).closeProgressDialog();

        }

        @Override
        public void onSearchDeviceFeature(ExtendedBluetoothDevice extendedBluetoothDevice, int i, int i1, Error error) {
          Log.d("====iccard=","onSearchDeviceFeature"+i+"=="+i1);


        }


        @Override
        public void onModifyICCardPeriod(ExtendedBluetoothDevice extendedBluetoothDevice, int i, long l, long l1, long l2, Error error) {
            Log.d("=onModifyICCardPeriod=","error=="+error);
            if (error==Error.SUCCESS){
                //同步校验锁时间
                cardno=l;
                long oldServiceTime = (long) get(getActivity(), null, SPContants.oldServiceTime, 0l);
                long oldPhoneTime = (long) get(getActivity(), null, SPContants.oldPhoneTime, 0l);
                long times = System.currentTimeMillis()-oldPhoneTime+oldServiceTime;
                mTTLockAPI.setLockTime(extendedBluetoothDevice,
                        0,
                        curKey.getLockVersion(),
                        curKey.getUnlockKey(),
                        times,
                        curKey.getLockFlagPos(),
                        curKey.getAesKeystr(),
                        curKey.getTimezoneRawOffset());
            }

        }

        @Override
        public void onDeleteICCard(ExtendedBluetoothDevice extendedBluetoothDevice, int i, long l, Error error) {
            Log.d("====iccarddelete=","error=="+error);

            if (error==Error.SUCCESS){
                userPresenter.deleteIcCard(uid,ActivityICCardList.localKey.getLockId(),ActivityICCardList.cardId);
            }
        }

        @Override
        public void onClearICCard(ExtendedBluetoothDevice extendedBluetoothDevice, int i, Error error) {
            Log.d("====iccard=","onClearICCard");

            if (error==Error.SUCCESS){
                userPresenter.clearIcCardList(uid,ActivityICCardList.localKey.getLockId());
            }
        }

        @Override
        public void onSetWristbandKeyToLock(ExtendedBluetoothDevice extendedBluetoothDevice, int i, Error error) {

        }

        @Override
        public void onSetWristbandKeyToDev(Error error) {

        }

        @Override
        public void onSetWristbandKeyRssi(Error error) {

        }


        @Override
        public void onFingerPrintCollection(ExtendedBluetoothDevice extendedBluetoothDevice, int i, Error error) {

        }

        @Override
        public void onModifyFingerPrintPeriod(ExtendedBluetoothDevice extendedBluetoothDevice, int i, long l, long l1, long l2, Error error) {

        }

        @Override
        public void onDeleteFingerPrint(ExtendedBluetoothDevice extendedBluetoothDevice, int i, long l, Error error) {

        }

        @Override
        public void onClearFingerPrint(ExtendedBluetoothDevice extendedBluetoothDevice, int i, Error error) {

        }

        @Override
        public void onSearchAutoLockTime(ExtendedBluetoothDevice extendedBluetoothDevice, int i, int i1, int i2, int i3, Error error) {
            Log.d("====iccard=","onSearchDeviceFeature");
        }

        @Override
        public void onModifyAutoLockTime(ExtendedBluetoothDevice extendedBluetoothDevice, int i, int i1, Error error) {

        }

        @Override
        public void onReadDeviceInfo(ExtendedBluetoothDevice extendedBluetoothDevice, String s, String s1, String s2, String s3, String s4) {

        }

        @Override
        public void onEnterDFUMode(ExtendedBluetoothDevice extendedBluetoothDevice, Error error) {

        }

        @Override
        public void onSearchBicycleStatus(ExtendedBluetoothDevice extendedBluetoothDevice, int i, int i1, Error error) {
            Log.d("====iccard=","onSearchDeviceFeature");
        }

        @Override
        public void onLock(ExtendedBluetoothDevice extendedBluetoothDevice, int i, int i1, int i2, long l, Error error) {
            Log.d("====iccard=","onLock==自动关锁");
        }

        @Override
        public void onScreenPasscodeOperate(ExtendedBluetoothDevice extendedBluetoothDevice, int i, int i1, Error error) {

        }

        @Override
        public void onAddICCard(ExtendedBluetoothDevice extendedBluetoothDevice, int status, int i, long l, Error error) {
            Log.d("====onAddICCard=",status+"===="+i+"==="+l+"error=="+error.toString());
            operateSuccess=true;
            if (error==error.SUCCESS&&status==2){//添加ic卡成功
                //修改时间的ic
                if (!ActivityAddICCard.endDate.equals("")){ //选择了时间
                    mTTLockAPI.modifyICPeriod(extendedBluetoothDevice,0,ActivityAddICCard.localKey.getLockVersion(),
                            ActivityAddICCard.localKey.getAdminPs(),ActivityAddICCard.localKey.getUnlockKey(),
                            ActivityAddICCard.localKey.getLockFlagPos(),l,
                            Long.parseLong(ActivityAddICCard.startDate)*1000,
                            Long.parseLong(ActivityAddICCard.endDate)*1000,
                            ActivityAddICCard.localKey.getAesKeystr(),ActivityAddICCard.localKey.getTimezoneRawOffset());
                }else {
                    userPresenter.addIcCard(uid,ActivityAddICCard.localKey.getLockId(),l+"",ActivityAddICCard.icCardName,ActivityAddICCard.startDate,ActivityAddICCard.endDate);
                    getActivity().sendBroadcast(new Intent(BleConstant.ADD_ICCARD));
                }

            }
//            mTTLockAPI.searchICCardNumber(extendedBluetoothDevice,0,ActivityAddICCard.localKey.getLockVersion(),
//                    ActivityAddICCard.localKey.getAdminPs(),
//                    ActivityAddICCard.localKey.getUnlockKey(),
//                    ActivityAddICCard.localKey.getLockFlagPos(),
//                    ActivityAddICCard.localKey.getAesKeystr());
//            mTTLockAPI.connect(extendedBluetoothDevice);


        }

        @Override
        public void onAddFingerPrint(ExtendedBluetoothDevice extendedBluetoothDevice, int status, int i, long l, Error error) {

        }

        @Override
        public void onRecoveryData(ExtendedBluetoothDevice extendedBluetoothDevice, int i, Error error) {

        }

    };

    private static final int REQUEST_PERMISSION_REQ_CODE = 1;

    /**
     * 权限请求
     */
    @TargetApi(Build.VERSION_CODES.M)
    public boolean requestPermission(String permission) {
        LogUtil.d("permission:" + permission, true);
        if (ContextCompat.checkSelfPermission(getActivity(), permission) != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), permission)) {
                LogUtil.w("not grant", true);
                return false;
            }
            //请求权限
            LogUtil.d("请求权限", DBG);
            requestPermissions(new String[]{permission}, REQUEST_PERMISSION_REQ_CODE);
            return false;
        }
        return true;
    }

    //TODO:
    private <K, V extends Parcelable> void broadcastUpdate(String action, K key, V value) {
        final Intent intent = new Intent(action);
        if (key != null) {
            Bundle bundle = new Bundle();
            bundle.putParcelable((String) key, value);
            intent.putExtras(bundle);

        }
        MyApplcation.ctx.sendBroadcast(intent);
    }

    private void toast(final String msg) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
            }
        });
    }

    @Override
    public void onSuccess(ResultData resultData) {
        // log(resultData.getId(), true, resultData.getData());

    }

    @Override
    public void onFailed(ResultError resultError) {
          log(resultError.getId(), false, resultError.getErrorCode().toLog());

    }

    private void log(ID id, boolean isSuccess, String log) {
        if (isSuccess) {
            ByAlert.alert(id.name() + ":第2个");
        } else {
            ByAlert.alert(TostKey.getStamp(log));
        }

    }

    private String getTime() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        return simpleDateFormat.format(new Date());
    }

     Key upLoadKey = new Key();
    //添加锁成功后上传数据
    public  void uploadData(){

        upLoadKey.setAccessToken(MyPreference.getStr(mContext, MyPreference.ACCESS_TOKEN));
        upLoadKey.setAdmin(true);
        upLoadKey.setLockVersion(ActivitySheBei.lockVersionString);
        upLoadKey.setLockName(ActivitySheBei.alisa);
        upLoadKey.setLockMac(ActivitySheBei.extendedBluetoothDevice.getAddress());
        upLoadKey.setAdminPs(adminPs);
        upLoadKey.setUnlockKey(unlockKey);
        upLoadKey.setAdminKeyboardPwd(adminKeyboardPwd);
        upLoadKey.setDeletePwd(ActivitySheBei.deletePwd);
        upLoadKey.setPwdInfo(ActivitySheBei.pwdInfo);
        upLoadKey.setTimestamp(ActivitySheBei.timestamp);
        upLoadKey.setAesKeystr(ActivitySheBei.aesKeystr);
        upLoadKey.setSpecialValue(ActivitySheBei.feature);
        upLoadKey.setBattery(ActivitySheBei.extendedBluetoothDevice.getBatteryCapacity());

//                key.setLockAlias(ActivitySheBei.alisa);
        //获取当前时区偏移量 可以传入-1 不考虑时区问题
        upLoadKey.setTimezoneRawOffset(TimeZone.getDefault().getOffset(System.currentTimeMillis()));
        upLoadKey.setModelNumber(ActivitySheBei.modelNumber);
        upLoadKey.setHardwareRevision(ActivitySheBei.hardwareRevision);
        upLoadKey.setFirmwareRevision(ActivitySheBei.firmwareRevision);
        SaveKeyBean.saveData("1", upLoadKey);
        toast("锁添加成功，正在上传服务端进行初始化操作");
        Log.d("addd===",ActivitySheBei.alisa);

        if ("".equals(sid)){
            keyPresenter.getAddMain(uid, "6323", ActivitySheBei.alisa,
                    ActivitySheBei.alisa, ActivitySheBei.extendedBluetoothDevice.getAddress(), unlockKey, "0",
                    ActivitySheBei.aesKeystr.toString(), ActivitySheBei.lockVersionString.toString(), adminPs, adminKeyboardPwd, ActivitySheBei.deletePwd,
                    ActivitySheBei.pwdInfo, ActivitySheBei.timestamp + "", ActivitySheBei.feature + "",
                    ActivitySheBei.extendedBluetoothDevice.getBatteryCapacity());
        }else {
            keyPresenter.getAddMain(sid, "6323", ActivitySheBei.alisa,
                    ActivitySheBei.alisa, ActivitySheBei.extendedBluetoothDevice.getAddress(), unlockKey, "0",
                    ActivitySheBei.aesKeystr.toString(), ActivitySheBei.lockVersionString.toString(), adminPs, adminKeyboardPwd, ActivitySheBei.deletePwd,
                    ActivitySheBei.pwdInfo, ActivitySheBei.timestamp + "", ActivitySheBei.feature + "",
                    ActivitySheBei.extendedBluetoothDevice.getBatteryCapacity());
        }

    }


    private void toRefreshData(String sid) {
        isLock= (boolean) SPUtils.get(MyApplcation.ctx,null,SPContants.ISLOCK,false);

        if (cz==1){

            if ("".equals(sid)){
                keyPresenter.getAddMain(uid, "6323", ActivitySheBei.alisa,
                        ActivitySheBei.alisa, ActivitySheBei.extendedBluetoothDevice.getAddress(), unlockKey, "0",
                        ActivitySheBei.aesKeystr.toString(), ActivitySheBei.lockVersionString.toString(), adminPs, adminKeyboardPwd, ActivitySheBei.deletePwd,
                        ActivitySheBei.pwdInfo, ActivitySheBei.timestamp + "", ActivitySheBei.feature + "",
                        ActivitySheBei.extendedBluetoothDevice.getBatteryCapacity());
            }else {
                keyPresenter.getAddMain(sid, "6323", ActivitySheBei.alisa,
                        ActivitySheBei.alisa, ActivitySheBei.extendedBluetoothDevice.getAddress(), unlockKey, "0",
                        ActivitySheBei.aesKeystr.toString(), ActivitySheBei.lockVersionString.toString(), adminPs, adminKeyboardPwd, ActivitySheBei.deletePwd,
                        ActivitySheBei.pwdInfo, ActivitySheBei.timestamp + "", ActivitySheBei.feature + "",
                        ActivitySheBei.extendedBluetoothDevice.getBatteryCapacity());
            }
        }else if (cz==2){
            if ("".equals(sid)){
                keyPresenter.myKey(uid, "",isLock);
            }else {
                keyPresenter.myKey(sid, "",isLock);
            }

            userPresenter.getOpenId(uid);//获取科技侠openid
        }else if (cz==5){ //白马解锁
            if ("".equals(sid)){
                keyTwoPresenter.onUnbindLock(uid, lockKeyId, deKeyId, "");
            }else {
                keyTwoPresenter.onUnbindLock(sid, lockKeyId, deKeyId, "");
            }
        }else if (cz==4){//白马锁列表
            if ("".equals(sid)){
                if (!mykey_sousuo.getText().toString().equals("")){
                    keyTwoPresenter.onMyKey(uid, mykey_sousuo.getText().toString().trim());
                }else {
                    keyTwoPresenter.onMyKey(uid, "");
                }
            }else {
                if (!mykey_sousuo.getText().toString().equals("")){
                    keyTwoPresenter.onMyKey(sid, mykey_sousuo.getText().toString().trim());
                }else {
                    keyTwoPresenter.onMyKey(sid, "");
                }
            }

        }
    }
}
